package com.yeskery.nut.extend.mcp;

import com.yeskery.nut.application.ServerEventContext;
import com.yeskery.nut.core.ControllerManager;
import com.yeskery.nut.core.Environment;
import com.yeskery.nut.core.Method;
import com.yeskery.nut.extend.mcp.core.Constants;
import com.yeskery.nut.extend.mcp.server.SseMcpMessageRequestHandler;
import com.yeskery.nut.extend.mcp.server.SseMcpServerInitializationRequestHandler;
import com.yeskery.nut.util.StringUtils;

import java.util.logging.Logger;

/**
 * 基于SSE的MCP Server插件
 * @author sprout
 * 2025-04-17 10:25
 */
public class McpSseServerPlugin extends BaseMcpServerPlugin {

    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(McpSseServerPlugin.class.getName());

    @Override
    public void beforeStart(ServerEventContext serverEventContext) {
        ControllerManager controllerManager = serverEventContext.getControllerManager();
        Environment environment = getApplicationContext().getBean(Environment.class);
        String sseEndpoint = getMcpSseEndpoint(environment);
        String messageEndpoint = getMcpMessageEndpoint(environment);
        controllerManager.registerController(new SseMcpServerInitializationRequestHandler(environment, messageEndpoint,
                getMcpSessionManager()), Method.GET, sseEndpoint);
        controllerManager.registerController(new SseMcpMessageRequestHandler(getApplicationContext(), getMcpSessionManager(), getMcpServerCapability()),
                Method.POST, messageEndpoint);
        logger.info("MCP[SSE], Endpoint[" + sseEndpoint + "], Alias[], Method[" + Method.GET + "]");
        logger.info("MCP[Message], Endpoint[" + messageEndpoint + "], Alias[], Method[" + Method.POST + "]");
    }

    /**
     * 获取MCP SSE Endpoint
     * @param environment 环境
     * @return MCP SSE Endpoint
     */
    private String getMcpSseEndpoint(Environment environment) {
        String endpoint = environment.getEnvProperty("nut.mcp.server.endpoint.sse");
        return StringUtils.isEmpty(endpoint) ? Constants.DEFAULT_SSE_ENDPOINT : endpoint;
    }

    /**
     * 获取MCP Message Endpoint
     * @param environment 环境
     * @return MCP Message Endpoint
     */
    private String getMcpMessageEndpoint(Environment environment) {
        String endpoint = environment.getEnvProperty("nut.mcp.server.endpoint.message");
        return StringUtils.isEmpty(endpoint) ? Constants.DEFAULT_MESSAGE_ENDPOINT : endpoint;
    }
}
